package com.wei.utils.wechat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wei.utils.http.HttpResult;
import com.wei.utils.http.HttpUtils;

public class WeChatRequest {
    private static final String wxUrl = "https://api.weixin.qq.com/sns/jscode2session";

    public static Code2Session login(String code, String appid, String secret) {
        Code2Session code2Session = null;

        HttpResult httpResult = HttpUtils.executeGet(wxUrl + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code");
        if (200 == httpResult.getStatusCode()) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                code2Session = mapper.readValue(httpResult.getContent(), Code2Session.class);
            } catch (JsonProcessingException ex) {
                code2Session = new Code2Session();
                code2Session.setErrcode("500");
                code2Session.setErrmsg(ex.getMessage());
            }
        } else {
            code2Session = new Code2Session();
            code2Session.setErrcode(httpResult.getStatusCode().toString());
            code2Session.setErrmsg("请求错误!");
        }
        return code2Session;
    }
}
